package com.haizhi.crm.biz.service.impl;

import com.haizhi.crm.biz.dao.HistoryViewDao;
import com.haizhi.crm.biz.model.HistoryViewDo;
import com.haizhi.crm.biz.service.HistoryViewService;
import com.haizhi.crm.common.constant.BizStatus;
import com.haizhi.crm.common.exception.UnexpectedStatusException;
import com.haizhi.crm.common.model.Response;
import com.haizhi.crm.common.util.CommonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by yangyijun on 2018/6/14.
 */
@Service
public class HistoryViewServiceImpl implements HistoryViewService {

    @Autowired
    private HistoryViewDao historyViewDao;

    @Override
    public Response recentView(String entityType, Integer limit) {
        try {
            Long userId = CommonUtils.getUserID();
            List<HistoryViewDo> historyViewDos = null;
            if (StringUtils.isNotBlank(entityType)) {
                historyViewDos = historyViewDao.findByEntityTypeAndUserId(userId, entityType, limit);
            } else {
                historyViewDos = historyViewDao.findByUserId(userId, limit);
            }
            return Response.success(historyViewDos);
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.HISTORY_VIEW_ERROR, e);
        }
    }

    @Override
    public Response save(String entityType, String entityKey, String title) {
        try {
            Long userId = CommonUtils.getUserID();
            List<HistoryViewDo> historyViewDos = historyViewDao.findBy(userId, entityType, entityKey);
            if (CollectionUtils.isEmpty(historyViewDos)) {
                HistoryViewDo historyViewDo = new HistoryViewDo();
                Date date = new Date();
                historyViewDo.setTitle(title);
                historyViewDo.setEntityType(entityType);
                historyViewDo.setEntityKey(entityKey);
                historyViewDo.setUserId(userId);
                historyViewDo.setCreatedDt(date);
                historyViewDo.setCreatedById(userId);
                historyViewDo.setUpdatedDt(date);
                historyViewDo.setUpdateById(userId);
                historyViewDo.setEnabledFlag("1" );
                historyViewDao.save(historyViewDo);
            } else {
                HistoryViewDo historyViewDo = historyViewDos.get(0);
                historyViewDo.setUpdatedDt(new Date());
                historyViewDao.save(historyViewDo);
            }
            return Response.success();
        } catch (Exception e) {
            throw new UnexpectedStatusException(BizStatus.SAVE_HISTORY_VIEW_ERROR, e);
        }
    }
}
